# -*- coding: utf-8 -*-
"""
作者: 肖麒
联系方式：QQ：1505448035
时间: 2025/4/24 15:34
文件作用：
"""
from api.QueryApi import QueryApi


def convert_to_srt(data, filename='subtitle.srt'):
    """
    将语音识别数据转换为SRT字幕格式（处理数组对象）

    Args:
        data: 包含文本和时间信息的数组
        filename: 保存的SRT文件名
    """

    def ms_to_time(ms):
        """将毫秒转换为SRT时间格式 (HH:MM:SS,mmm)"""
        hours = ms // 3600000
        minutes = (ms % 3600000) // 60000
        seconds = (ms % 60000) // 1000
        milliseconds = ms % 1000
        return f"{hours:02d}:{minutes:02d}:{seconds:02d},{milliseconds:03d}"

    # 创建SRT内容
    srt_content = ""

    # 遍历数组中的每个字幕项
    for index, item in enumerate(data, 1):
        start_time_str = ms_to_time(item['start_time'])
        end_time_str = ms_to_time(item['end_time'])

        srt_content += f"{index}\n"
        srt_content += f"{start_time_str} --> {end_time_str}\n"
        srt_content += f"{item['text']}\n\n"

    # 保存到文件
    with open(filename, 'w', encoding='utf-8') as f:
        f.write(srt_content)

    print(f"SRT字幕文件已保存为: {filename}")
    return filename


# 使用示例
query_api = QueryApi()
json_data = query_api.get_query()
data = json_data.get('data')
utterances = data.get('utterances')

# 调用函数生成SRT文件
convert_to_srt(utterances)
